const role = require('../module/role')

const main_role_add = async (ctx, next) => {
  try {
    const {
      nickName,
      permission
    } = ctx.request.body

    const resCreateRole = await role.create({
      nickName,
      permission
    })
    if (resCreateRole) {
      ctx.body = {
        code: 0,
        msg: '角色添加成功',
        data: resCreateRole
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '角色添加失败',
        data: null
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: `角色添加失败，失败原因：${error}`,
      data: null
    }
  }
}


const main_role_delete = async (ctx, next) => {
  try {
    const {
      _id
    } = ctx.request.body
  
    const resDelRole = await role.remove({
      _id
    })

    if (resDelRole.deletedCount >= 1) {
      ctx.body = {
        code: 0,
        msg: '角色删除成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '角色删除失败'
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: `角色删除失败,失败原因${error}`
    }
  }
}

const main_role_change = async (ctx, next) => {
  try {
    // 前端给的东西
    const {
      _id,
      nickName,
      permission
    } = ctx.request.body

    // 通过第一个参数，找到第二个参数并修改
    const resUpdateRole = await role.findByIdAndUpdate(_id,{
      nickName,
      permission
    })

    if (resUpdateRole) {
      ctx.body = {
        code: 0,
        msg: '角色信息修改成功',
        data: resUpdateRole
      }
    } else {
      ctx.body = {
        code: -1,
        msg: `角色信息修改失败,失败原因${error}`
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: `角色信息修改失败,失败原因${error}`
    }
  }
}

const main_role_search = async (ctx, next) => {
  try {
    const resSearch = await role.find()
  
    if (resSearch !== null) {
      ctx.body = {
        code: 0,
        msg: '角色信息获取成功',
        data: resSearch
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '角色信息获取失败',
        data: null
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: `角色信息获取失败,失败原因：${error}`,
      data: null
    }
  }
}

const view_single_role = async (ctx, next) => {
  try {
    const {
      _id
    } = ctx.request.query
    console.log(_id)
  
    const resViewSingleRole = await role.findById(_id)

    if (resViewSingleRole !== null) {
      ctx.body = {
        code: 0,
        msg: '角色信息获取成功',
        data: resViewSingleRole
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '角色信息获取失败',
        data: null
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: '角色信息获取失败',
      data: null
    }
  }
}


//get
module.exports = {
  'GET /roleSearch': main_role_search,
  'POST /roleChange': main_role_change,
  'POST /roleDelete': main_role_delete,
  'POST /roleAdd': main_role_add,
  'GET /roleSingleView': view_single_role
}